<template>
	<el-upload :action="uploadAction" :accept="uploadAccept" :headers="uploadHeader" :file-list="fileList" v-bind="uploadConfig">
		<el-button type="primary" class="uploadBtn" icon="el-icon-upload2">上传文件</el-button>
		<div slot="tip" class="tips">
			<label>建议：上传文件</label>
			<span v-if="!!uploadSizes">
				大小不超过
				<font color="#f00">{{ uploadSizes }}MB</font>
			</span>
			<span v-if="!!uploadSizes && !!uploadAccepts">且</span>
			<span v-if="!!uploadAccepts">
				格式为
				<font color="#606266">{{ uploadAccepts }}</font>
			</span>
		</div>
	</el-upload>
</template>

<script>
import { mapGetters } from 'vuex';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	name: 'gxFileUploader',
	mixins: [emitter],
	props: {
		value: { type: String, default: '' },
		//上传类型
		type: { type: String, default: '2' },
		//是否多选
		multiple: { type: Boolean, default: false },
		//上传文件个数
		limit: { type: Number, default: 5 }
	},
	data() {
		let baseURL = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
		return {
			fileString: this.value,
			uploadAction: `${baseURL}tbSysAttachment/upload`, // 上传的图片服务器地址
			uploadConfig: {
				ref: 'upload',
				limit: this.limit,
				multiple: this.multiple,
				class: 'multiple_file_upload',
				onRemove: this.handleUploadRemove,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload,
				data: { showType: '5', type: this.type }
			},
			fileList: [],
			uploadFiles: []
		};
	},
	computed: {
		...mapGetters(['token', 'dictConst']),
		uploadTypes() {
			if (this.type === '1') {
				return { type: 'SYSTEM_ATTA_TYPE', size: 'SYSTEN_ATTA_SIZE' };
			} else if (this.type === '2') {
				return { type: 'BUSI_ATTA_TYPE', size: 'BUSI_ATTA_SIZE' };
			} else if (this.type === '3') {
				return { type: 'JOURNALISM_ATTA_TYPE', size: 'JOURNALISM_ATTA_SIZE' };
			} else if (this.type === '4') {
				return { type: 'IMAGE_ATTA_TYPE', size: 'IMAGE_ATTA_SIZE' };
			} else if (this.type === '5') {
				return { type: 'DISKDIR_ATTA_TYPE', size: 'DISKDIR_ATTA_SIZE' };
			} else if (this.type === '6') {
				return { type: 'CLIP_ATTA_TYPE', size: 'CLIP_ATTA_SIZE' };
			} else if (this.type === '7') {
				return { type: 'CLIPTEMP_ATTA_TYPE', size: 'CLIPTEMP_ATTA_SIZE' };
			} else if (this.type === '8') {
				return { type: 'SYS_FFCONFIG1_TYPE', size: 'SYS_FFCONFIG1_SIZE' };
			} else if (this.type === '9') {
				return { type: 'SYS_FFCONFIG2_TYPE', size: 'SYS_FFCONFIG2_SIZE' };
			} else if (this.type === '10') {
				return { type: 'SYS_FFCONFIG3_TYPE', size: 'SYS_FFCONFIG3_SIZE' };
			} else if (this.type === '11') {
				return { type: 'SYS_FFCONFIG4_TYPE', size: 'SYS_FFCONFIG4_SIZE' };
			} else if (this.type === '12') {
				return { type: 'SYS_FFCONFIG5_TYPE', size: 'SYS_FFCONFIG5_SIZE' };
			} else if (this.type === '13') {
				return { type: 'SYS_FFCONFIG6_TYPE', size: 'SYS_FFCONFIG6_SIZE' };
			} else {
				return { type: 'SYSTEM_ATTA_TYPE', size: 'SYSTEN_ATTA_SIZE' };
			}
		},
		uploadSizes() {
			return this.dictConst[this.uploadTypes.size];
		},
		uploadAccepts() {
			return this.dictConst[this.uploadTypes.type];
		},
		uploadAccept() {
			let suffixArr = this.uploadAccepts.split(',').map((item) => `.${item}`);
			return suffixArr.join();
		},
		uploadHeader() {
			return { Authorization: this.token, userButton: 'a395e5424cad4effbd645407b1241213' };
		}
	},
	watch: {
		value(val) {
			this.fileString = val;
		},
		fileString: {
			handler(val) {
				this.$emit('input', val);
				this.dispatch('ElFormItem', 'el.form.change', [val]);
				if (!!val && this.$isJSON(val)) {
					this.fileList = JSON.parse(val);
				} else {
					this.$nextTick(() => {
						this.$refs['upload'].clearFiles();
					});
				}
			},
			immediate: true
		},
		uploadFiles(arr) {
			let successFiles = arr.filter((n) => n.status === 'success');
			this.fileString = this.formatFileList(successFiles);
		}
	},
	methods: {
		// 上传前loading加载
		handleBeforeUpload(file) {
			let suffixArr = file.name.split('.');
			let suffix = suffixArr[suffixArr.length - 1];
			let acceptArr = this.uploadAccepts.split(',');
			if (!acceptArr.some((n) => n === suffix)) {
				this.$showCustomMessage('warning', '请上传规定类型的文件！');
				return false;
			}
			if (file.size > this.uploadSizes * 1024 * 1024) {
				this.$showCustomMessage('warning', '请上传规定大小的文件！');
				return false;
			}
		},

		// 文件个数超出
		handleExceed() {
			this.$showCustomMessage('success', `上传文件数量不能超过 ${this.limit} 个！`);
		},

		//删除列表变化
		handleUploadRemove(file, fileList) {
			this.$nextTick(() => {
				this.uploadFiles = fileList;
			});
		},

		handleUploadSuccess(res, file, fileList) {
			let index = fileList.findIndex((n) => n.uid === file.uid);
			if (res.code !== '0') {
				fileList.splice(index, 1);
			}
			this.uploadFiles = fileList;
		},

		//格式化上传文件列表
		formatFileList(arr) {
			let emitFiles = arr.map((item) => {
				let data = {};
				if (!item.response) {
					data = { ...item };
				} else {
					data = item.response.data[0];
					data['name'] = data.oldName;
					data['url'] = data.originalAddr;
					data['suffix'] = data.attrSuffixStr;
				}
				return {
					id: data.id,
					url: data.url,
					name: data.name,
					status: 'success',
					suffix: data.suffix,
					newName: data.newName,
					absoluteAddr: data.absoluteAddr
				};
			});
			return JSON.stringify(emitFiles);
		}
	}
};
</script>

<style lang="scss" scoped>
.multiple_file_upload::v-deep {
	.tips {
		color: #999;
		font-size: 14px;
		margin-top: 10px;
		line-height: 20px;
	}
}
</style>
